<script setup lang="ts">
import { ref, onMounted } from 'vue';
import Taro, { 
  getCurrentInstance, 
  showToast, 
  showLoading, 
  hideLoading, 
  requestPayment 
} from '@tarojs/taro';
import { request } from '@/service/request';
import { storeToRefs } from 'pinia';
import { useAuthStore } from '@/store';
import { IconFont } from '@nutui/icons-vue-taro';
const { nurseUser, openid } = storeToRefs(useAuthStore());

interface ArticleDetail {
  id: string;
  title: string;
  createTime: string;
  contain: string;
  price: number;
}

const { router } = getCurrentInstance() as any;
const { id = '' } = router?.params || {};

const article = ref<ArticleDetail>({
  id: 'mock-1',
  title: '护理健康小知识',
  createTime: '2024-01-01 09:00',
  contain: '<p>模拟文章内容：保持良好的作息和饮食习惯，有助于身体健康。长期坚持健康的生活方式可以预防多种疾病，提高生活质量。建议每天保持7-8小时睡眠，均衡饮食，适量运动。</p>',
  price: 9.9
});

const loading = ref(false);
const hasPurchased = ref(false);

const mockArticle: ArticleDetail = {
  id: 'mock-1',
  title: '护理健康小知识',
  createTime: '2024-01-01 09:00',
  contain: '<p>模拟文章内容：保持良好的作息和饮食习惯，有助于身体健康。长期坚持健康的生活方式可以预防多种疾病，提高生活质量。建议每天保持7-8小时睡眠，均衡饮食，适量运动。</p>',
  price: 9.9
};

definePageConfig({
  navigationBarTitleText: '文章详情'
});

/** 获取文章详情 */
const fetchArticleDetail = async () => {
  if (!id) return;
  try {
    showLoading({ title: '加载中' });
    const { error, success } = await request.get<ArticleDetail>(`/news_shop/newsShop/queryById?id=${id}`, {}, {
      useErrMsg: true
    });
    if (!error && success) {
      article.value = success;
      if(article.value.price == 0){
        hasPurchased.value = true;
      }
      else{
        checkBuy();
      }

    } else {
      article.value = mockArticle;
      showToast({ title: '已加载模拟数据', icon: 'none' });
    }
  } catch (error) {
    article.value = mockArticle;
    showToast({ title: '已加载模拟数据', icon: 'none' });
  } finally {
    hideLoading();
  }
};

const templateId = 'nuiO7yhm3wLMa6WsDHE3g-m5WlrW3IjE7k25RmUK2PI';

function callCan(){
  Taro.requestSubscribeMessage({
    tmplIds: [templateId], // 替换为实际模板 ID
    success: res => {
      if (res.errMsg === 'requestSubscribeMessage:ok') {
        // 用户同意授权，可调用后端接口发送消息
        // this.sendMessageToServer();
        setMsg()
      }
    },
    fail: err => {
      // 调起订阅消息失败
    }
  });
}

async function setMsg(){
  Taro.login({
    success: async function(res){
      // const data = JSON.stringify({
      //   'name1.DATA': '张三', // 患者OpenID（需提前绑定）
      //   'name2.DATA': '战士', // 医生姓名
      //   'date4.DATA': '2024/12/09' // 接诊时间
      // })
      const page = 'pages/index/index'
      const rs = await request.post<any>(`/WeChat/sendSubscribeMsg?code=${res.code}&templateId=${templateId}&page=${page}`, {}, {
        useErrMsg: true
      });
    }
  })
  // openid
  // const res = await request.post<any>(`/WeChat/sendSubscribeMsg?openId=${openid.value}&templateId=${templateId}`, {}, {
  //       useErrMsg: true
  // });
  // res msg
}


const checkBuy = async () => {
  //news_order/newsOrder/listByWeChat?userId=${nurseUser.value.id}&newsId=${id}&status=2
  const { error, success } = await request.get<any>(`/news_order/newsOrder/listByWeChat`, {
    userId: nurseUser.value.id,
    newsId: id,
    status: 2
  }, {
    useErrMsg: true
  });
  if(error){
    hasPurchased.value = false
  }else{
    hasPurchased.value = success?.length > 0
  }
}

// checkBuy()

/** 购买文章 */
const buyArticle = async () => {
  // buy
  // callCan();
  // return;

  if (loading.value || hasPurchased.value) return;
  loading.value = true;
  try {
    showLoading({ title: '下单中' });
    const { error, success } = await request.post<any>('/news_order/newsOrder/addByWeChat', {
      newsId: article.value.id,
      userId: nurseUser.value.id,

    }, {
      useErrMsg: true
    });
    if (error || !success) {
      showToast({ title: error?.message || '下单失败', icon: 'error' });
      return;
    }

    const { timestamp, noncestr, package: packAge, sign } = success;


await requestPayment({
    timeStamp: timestamp,
    nonceStr: noncestr,
    package: packAge,
    paySign: sign,
    signType: 'RSA',
      success: () => {
        showToast({ title: '支付成功', icon: 'success' });
        hasPurchased.value = true;
      },
      fail: () => {
        showToast({ title: '支付失败', icon: 'error' });
      }
    });
  } catch (error) {
    showToast({ title: '下单失败', icon: 'error' });
  } finally {
    hideLoading();
    loading.value = false;
  }
};

onMounted(() => {
  fetchArticleDetail();
  // checkBuy()
});
</script>

<template>
  <view class="min-h-screen bg-gray-50 pb-[200rpx] relative">
    <!-- 全局遮罩层 -->
    <view 
      v-if="!hasPurchased"
      class="fixed inset-0 bg-black bg-opacity-20 z-10 pointer-events-none"
    ></view>
    <!-- 文章头部 -->
    <view class="bg-white p-[32rpx] mb-[20rpx] relative">
      <view class="flex items-center justify-between mb-[16rpx]">
        <view class="flex-1">
          <view class="text-[40rpx] font-bold text-gray-800 mb-[16rpx] leading-tight">{{ article.title }}</view>
          <view class="text-[24rpx] text-gray-500 flex items-center">
            {{ article.createTime }}
          </view>
        </view>
        <!-- 未购买时的锁定标识 -->
        <view 
          v-if="!hasPurchased"
          class="flex items-center px-[16rpx] py-[8rpx] bg-red-50 rounded-full border border-red-200"
        >
          <view class="w-[24rpx] h-[24rpx] bg-red-500 rounded-full flex items-center justify-center mr-[8rpx]">
            <!-- <IconFont name="dongdong" size="12" color="#ffffff"></IconFont> -->
            <IconFont font-class-name="iconfont" class-prefix="icon" name="suo" size="12" color="#ffffff"></IconFont>
          </view>
          <text class="text-[20rpx] text-red-600 font-medium">付费</text>
        </view>
      </view>
    </view>

    <!-- 文章内容区域 -->
    <view class="relative bg-white p-[32rpx] mb-[20rpx]">
      <!-- 内容容器，限制显示行数 -->
      <view 
        class="text-[28rpx] text-gray-700 leading-[1.8] relative"
        :class="!hasPurchased ? 'max-h-[112rpx] overflow-hidden locked-content' : ''"
      >
        <!-- <view v-html="article.contain"></view> -->
        <rich-text :nodes="article.contain"></rich-text>
        
        <!-- 未购买时的遮罩层 -->
        <view 
          v-if="!hasPurchased"
          class="absolute inset-0 bg-gradient-to-b from-white via-white to-transparent"
          style="background: linear-gradient(to bottom, rgba(255,255,255,1) 0%, rgba(255,255,255,1) 60%, rgba(255,255,255,0.8) 80%, rgba(255,255,255,0) 100%);"
        ></view>
        
        <!-- 未购买时的锁定图标 -->
        <view 
          v-if="!hasPurchased"
          class="absolute bottom-[-40rpx] right-0 flex items-center"
        >
          <view class="w-[32rpx] h-[32rpx] bg-[#667eea] rounded-full flex items-center justify-center mr-[8rpx]">
            <!-- <IconFont name="dongdong" size="16" color="#ffffff"></IconFont> -->
            <IconFont font-class-name="iconfont" class-prefix="icon" name="suo" size="16" color="#ffffff"></IconFont>
          </view>
          <text class="text-[24rpx] text-[#667eea]">已锁定</text>
        </view>
      </view>
      
      <!-- 未购买时的提示条 -->
      <view 
        v-if="!hasPurchased && article.price > 0"
        class="mt-[60rpx] py-[24rpx] px-[32rpx] bg-gradient-to-r from-blue-50 to-purple-50 rounded-[16rpx] border border-blue-100 flex items-center"
      >
        <view class="flex items-center mr-[16rpx]">
          <view class="w-[40rpx] h-[40rpx] bg-[#667eea] rounded-full flex items-center justify-center">
            <!-- <IconFont name="dongdong" size="20" color="#ffffff"></IconFont> -->
            <IconFont font-class-name="iconfont" class-prefix="icon" name="suo" size="20" color="#ffffff"></IconFont>
          </view>
        </view>
        <view class="flex-1">
          <text class="text-[28rpx] font-bold text-[#333333] block">解锁完整内容</text>
          <text class="text-[24rpx] text-[#666666] block">购买后可阅读全文</text>
        </view>
        <nut-button 
          type="primary" 
          size="small" 
          class="gradient-button"
          @tap="buyArticle"
          :loading="loading"
        >
          立即解锁
        </nut-button>
      </view>
    </view>

    <!-- 底部购买栏 -->
    <view
      v-if="article.price > 0"
      class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-100 p-[24rpx] flex items-center safe-area-bottom shadow-top z-20"
    >
      <view class="flex flex-1 items-center">
        <view class="flex items-center">
          <view class="w-[40rpx] h-[40rpx] bg-gradient-to-r from-[#667eea] to-[#764ba2] rounded-full flex items-center justify-center mr-[16rpx]">
            <!-- <IconFont name="dongdong" size="20" color="#ffffff"></IconFont> -->
            <IconFont font-class-name="iconfont" class-prefix="icon" name="suo" size="20" color="#ffffff"></IconFont>
          </view>
          <view>
            <text class="text-[24rpx] text-gray-500 block">解锁价格</text>
            <view class="text-[36rpx] font-bold text-red-500">¥{{ Number(article.price).toFixed(2) }}</view>
          </view>
        </view>
      </view>
      
      <nut-button
        type="primary"
        size="large"
        class="flex-1 ml-[32rpx] gradient-button"
        :loading="loading"
        :disabled="hasPurchased"
        @tap="buyArticle"
      >
        {{ loading ? '处理中...' : hasPurchased ? '已购买' : '立即解锁' }}
      </nut-button>
    </view>
  </view>
</template>

<style>
/* 添加顶部阴影效果 */
.shadow-top {
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
}

/* 文章内容样式 */
.text-gray-700 p {
  margin-bottom: 32rpx;
}

/* 安全区域适配 */
.safe-area-bottom {
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
}

/* 遮罩层样式 */
.bg-gradient-to-b {
  background: linear-gradient(to bottom, rgba(255,255,255,1) 0%, rgba(255,255,255,1) 60%, rgba(255,255,255,0.8) 80%, rgba(255,255,255,0) 100%);
}

/* 锁定状态样式 */
.locked-content {
  position: relative;
  overflow: hidden;
}

.locked-content::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60rpx;
  background: linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
  pointer-events: none;
}

/* 按钮渐变效果 */
.gradient-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.gradient-button:active {
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.3);
}
</style>